# -*- coding: utf-8 -*-
# django admin删除数据库记录的同时删除文件 2023.12.25
# 原文链接：https://blog.csdn.net/weixin_41660414/article/details/104114415

import os
from django.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.conf import settings
    
    
# 上传图片  设置media以显示图片
class Course(models.Model):
    image = models.ImageField(default='', upload_to='img/', verbose_name='图片logo', max_length=100)

## 添加监听器 
@receiver(post_delete, sender=Course)
def delete_upload_files(sender, instance, **kwargs):
    files = getattr(instance, 'image')
    if not files:
        return
    fname = os.path.join(settings.MEDIA_ROOT, str(files))
    if os.path.isfile(fname):
        os.remove(fname)

